<template>
  <div>
    <el-dialog
      :title="'用户：' + username + ' 修改密码'"
      v-model="state.isShow"
      lock-scroll
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      draggable
      align-center
      width="400px"
      @closed="closed"
    >
      <ul>
        <li class="flex items-center bg-[#e5f1f5] border rounded-[6px]">
          <div class="w-[100px] pl-2">密码</div>
          <div class="flex-1 w-0">
            <el-input v-model="form.password" placeholder="请输入密码" />
          </div>
        </li>
        <li class="flex items-center bg-[#e5f1f5] border rounded-[6px] mt-[10px]">
          <div class="w-[100px] pl-2">确认密码</div>
          <div class="flex-1 w-0">
            <el-input v-model="form.newPassword" placeholder="请输入确认密码" />
          </div>
        </li>
      </ul>
      <template #footer>
        <el-button @click="closed">取 消</el-button>
        <el-button
          :disabled="state.updating"
          :loading="state.updating"
          type="primary"
          @click="confirm"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { message } from "@/utils/message";
import { debounce } from "lodash-es";
import { reqUserResetPassword } from "@/api/user";

const props = defineProps({
  username: {
    type: String,
    default: ""
  },
  uid: {
    type: Number,
    default: 0
  }
});
const emit = defineEmits(["update"]);
const state = reactive({
  isShow: false,
  updating: false
});
const form = reactive({
  password: "",
  newPassword: ""
});
const closed = () => {
  form.password = "";
  form.newPassword = "";
  state.isShow = false;
};
const open = () => {
  state.isShow = true;
};
const confirm = debounce(async () => {
  if (!props.uid) {
    message.warning("非法操作");
    return false;
  }
  if (!form.password) {
    message.warning("请输入密码");
    return false;
  }
  if (!form.newPassword) {
    message.warning("请输入确认密码");
    return false;
  }
  if (form.password != form.newPassword) {
    message.warning("确认密码不正确");
    return false;
  }
  state.updating = true;
  try {
    await reqUserResetPassword({
      UserId: props.uid,
      Password: form.password,
      newPassword: form.newPassword
    });
    state.updating = false;
    emit("update");
    message.success("修改密码成功");
    setTimeout(() => {
      closed();
    }, 200);
  } catch (error) {
    state.updating = false;
    console.log(error);
  }
}, 500);
defineExpose({
  open
});
</script>
<style scoped lang="scss">
:deep(.el-dialog__body) {
  padding: 20px;
}
</style>
